﻿
using Microsoft.Office.Interop.Outlook;
using System.Collections.Specialized;
namespace Revolutions.OutlookTreeExpander
{
    class TreeNodeExpander
    {
        private string _startUpTreeNode;
        private StringCollection _treeNodesToOpen;
        private Application _application;

        public TreeNodeExpander(Application application, string startUpTreeNode, StringCollection treeNodesToOpen)
        {
            _application = application;
            _startUpTreeNode = startUpTreeNode;
            _treeNodesToOpen = treeNodesToOpen;
        }

        public void ExpandOutlookTree()
        {
            _application.ActiveExplorer().CurrentFolder = _application.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

            foreach (string path in _treeNodesToOpen)
            {
                Folder f = GetFolder(path);
                if (f != null)
                {
                    ExpandTreeNode(f);
                }
            }

            Folder selectedStartupFolder = GetFolder(_startUpTreeNode);
            if (selectedStartupFolder != null)
            {
                _application.ActiveExplorer().CurrentFolder = selectedStartupFolder;
            }
        }

        private Folder GetFolder(string folderPath)
        {
            Folder returnFolder = null;

            try
            {
                // Remove leading "\" characters.
                folderPath = folderPath.TrimStart('\\');

                // Split the folder path into individual folder names.
                string[] folders = folderPath.Split('\\');

                // Retrieve a reference to the root folder.
                returnFolder = _application.Session.Folders[folders[0]] as Folder;

                // If the root folder exists, look in subfolders.
                if (returnFolder != null)
                {
                    Folders subFolders = null;
                    string folderName;

                    // Look through folder names, skipping the first
                    // folder, which you already retrieved.
                    for (int i = 1; i < folders.Length; i++)
                    {
                        folderName = folders[i];
                        subFolders = returnFolder.Folders;
                        returnFolder = subFolders[folderName] as Folder;
                    }
                }
            }
            catch
            {
                // Do nothing at all -- just return a null reference.
                returnFolder = null;
            }

            return returnFolder;
        }

        private void ExpandTreeNode(Folder folder)
        {
            if (folder.Folders.Count > 0)
            {
                folder = folder.Folders.GetFirst() as Folder;
            }

            _application.ActiveExplorer().CurrentFolder = folder;
        }
    }
}
